package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.pojos.ApAssociateWords;
import com.heima.search.service.ApAssociateSearchService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ApAssociateSearchServiceImpl implements ApAssociateSearchService {

@Autowired
private MongoTemplate mongoTemplate;


    @Override
    public ResponseResult search(UserSearchDto userSearchDto) {
        if(userSearchDto==null || StringUtils.isBlank(userSearchDto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }


        int page=userSearchDto.getPageSize();
        if(page<0|| page>10){
            page=10;
        }

        Query query = Query.query(Criteria.where("associateWords").regex(".*"+userSearchDto.getSearchWords()+".*"));
        query.limit(page);
        List<ApAssociateWords> apAssociateWords = mongoTemplate.find(query, ApAssociateWords.class);

        return ResponseResult.okResult(apAssociateWords);
    }
}
